package com.black.common.mybatis;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.black.common.auth.UserContextHolder;
import org.apache.ibatis.reflection.MetaObject;

import java.time.LocalDateTime;

/**
 * @author linwenfeng
 */
public class BaseEntityMetaObjectHandler implements MetaObjectHandler {

    private static final String CREATOR = "creator";
    private static final String CREATED_NAME = "creatorName";
    private static final String CREATE_TIME = "createTime";
    private static final String UPDATER = "updater";
    private static final String UPDATED_NAME = "updaterName";
    private static final String UPDATE_TIME = "updateTime";
    private static final String VALID = "valid";

    /**
     * 插入的时候自动填充数据
     *
     * @param metaObject 需要操作元数据
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        this.setFieldValByName(CREATOR, UserContextHolder.getUserIdWithDefault(), metaObject);
        this.setFieldValByName(CREATE_TIME, LocalDateTime.now(), metaObject);
        this.setFieldValByName(UPDATER, UserContextHolder.getUserIdWithDefault(), metaObject);
        this.setFieldValByName(UPDATE_TIME, LocalDateTime.now(), metaObject);
        Object stateVal = this.getFieldValByName(VALID, metaObject);
        if (stateVal == null) {
            this.setFieldValByName(VALID, 1, metaObject);
        }
        if (metaObject.hasSetter(CREATED_NAME)) {
            this.setFieldValByName(CREATED_NAME, UserContextHolder.getUsernameWithDefault(), metaObject);
        }
        if (metaObject.hasSetter(UPDATED_NAME)) {
            this.setFieldValByName(UPDATED_NAME, UserContextHolder.getUsernameWithDefault(), metaObject);
        }

    }

    /**
     * 更新时自动填充业务数据
     *
     * @param metaObject 需要操作元数据
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        this.setFieldValByName(UPDATE_TIME, LocalDateTime.now(), metaObject);
        this.setFieldValByName(UPDATER, UserContextHolder.getUserId(), metaObject);
        if (metaObject.hasSetter(UPDATED_NAME)) {
            this.setFieldValByName(UPDATED_NAME, UserContextHolder.getUsername(), metaObject);
        }
    }
}
